class PostsController < ApplicationController
  before_action :current_admin, only: [:new, :edit, :update, :destroy]
  before_action :set_post, only: [:show, :edit, :update, :destroy]


  def destroy
    @post.delete
    flash[:success] = "删除成功"
    redirect_to request.referrer || posts_path
  end


  def new
    @post = Post.new
  end

  def show
    @post = Post.find(params[:id])
    @feed_items = @post.post_relationships.paginate(page: params[:page]).order(created_at: :desc)
    @relationship = Relationship.new
    respond_to do |format|
      format.html { render :show }
      format.json { render json: @post }

    end
  end

  def index
    @posts = Post.all.paginate(page: params[:page]).order(created_at: :desc)
    @post_type_items = PostType.all
  end

  def create
    user_id = session[:user_id]
    @post = Post.new(post_params)
    respond_to do |format|
      @post.user_id = user_id
      if @post.save
        format.html { redirect_to action: :index, notice: '贴子发布成功' }
        format.json { render :index, status: :created, location: @user }
      else
        format.html { render :new }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  def edit
    @post = Post.find(params[:id])
  end

  def update
    respond_to do |format|
      if @post.update(post_params)
        format.html { redirect_to action: :index, notice: 'User was successfully updated.' }
        format.json { render :show, status: :ok, location: @user }
      else
        format.html { render :edit }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  private
  def post_params
    params.require(:post).permit(:title, :context, :picture, :image, :attachment)
  end

  def set_post
    @post = Post.find(params[:id])
  end


end

